# coding:utf-8
class Admin::RecommandsController < AdminController
  respond_to :html, :json

  set_tab :statistics
  set_tab :recommands, :sub_nav
  before_filter :setup, only: [:index]

  def index
    params[:recommand] ||= {}
    params[:recommand][:group] ||= 'recommander_id'
    owners = { 'recommander_id' => :recommander, 'terminal_id, recommander_id' => [:terminal, :recommander] }
    order = params[:recommand][:group] == 'recommander_id' ? 'total DESC' : 'terminal_id'
    recommands = Recommand.order(order)
    recommands = recommands.after_date(params[:recommand][:start_date]) if params[:recommand][:start_date].present?
    recommands = recommands.before_date(params[:recommand][:end_date]) if params[:recommand][:end_date].present?
    recommands = recommands.select([params[:recommand][:group], 'COUNT(id) AS total'])
      .group(params[:recommand][:group])


    respond_to do |format|
      format.js {
        @recommands = recommands.all
      }
      format.html {
        @level_mode = 
          params[:recommand][:group] == 'recommander_id' && params[:recommand][:stay].present? && params[:recommand][:promotion].present?
        @adjust_mode = params[:commit] == '实施'
        @auto_mode = params[:commit] == '自动'
          
        should_include = @level_mode ? { owners[params[:recommand][:group]] => :account_group } : owners[params[:recommand][:group]] 

        @recommands = recommands.all
        clean_recommands @recommands, params[:recommand][:group] == 'recommander_id'

        if @level_mode
          stay = [params[:recommand][:stay].to_i, 0].max
          promotion = [params[:recommand][:promotion].to_i, 1].max
          @recommands.each do |r|
            r.recommander.level_before = r.recommander.level
            r.recommander.level_change = Account.determine_level_change r.respond_to?(:total) ? r.total.to_i : 0, stay, promotion
            r.recommander.level_after =  Account.determine_level_after r.recommander.account_group.levels, r.recommander.level, r.recommander.level_change
            r.recommander.level_after ||= r.recommander.level_before || 1.0
            r.recommander.update_column(:level, r.recommander.level_after) if @adjust_mode
          end

          # auto mode will remember all the settings
          if @auto_mode
            recommander_level_stay = stay
            recommander_level_promotion = promotion
            recommander_from_day = 1.day.since.strftime('%Y-%m-%d')

            if params[:recommand][:date_gap].present?
              recommander_gap_days = [params[:recommand][:date_gap].to_i, 1].max
            else
              recommander_gap_days = 3
            end
            SiteSetting.create_or_update_from_hash(
              recommander_level_stay:      recommander_level_stay,
              recommander_level_promotion: recommander_level_promotion, 
              recommander_from_day:        recommander_from_day,
              recommander_gap_days:        recommander_gap_days)
            RecommandHistory.create(
              level_stay:      recommander_level_stay,
              level_promotion: recommander_level_promotion, 
              from_day:        recommander_from_day,
              gap_days:        recommander_gap_days
            )
          end
        end

        if @adjust_mode || @auto_mode
          if params[:recommand][:group] != 'recommander_id'
            @notice = "设备无法运用策略，只能查看榜单，因为设备与帐号之间没有直接关系"
          elsif !@level_mode
            @notice = "运用策略前，请选择保级推荐数和升级推荐数"
          elsif @adjust_mode
  
            @notice = "本策略已手动生效，生效结果见下图所示，计算规则：保级推荐数（#{stay}），升级推荐数（#{promotion}）"
          else
           @notice = "本策略将于#{recommander_from_day}晚上零点开始每隔#{recommander_gap_days}天生效一次，计算规则：保级推荐数（#{recommander_level_stay}），升级推荐数（#{recommander_level_promotion}）"
          end
        elsif SiteSetting.find_by_key('recommander_level_stay').present?
          @notice = "当前策略于#{SiteSetting.find_by_key('recommander_from_day').value}晚上零点开始每隔#{SiteSetting.find_by_key('recommander_gap_days').value}天生效一次，计算规则：保级推荐数（#{SiteSetting.find_by_key('recommander_level_stay').value}），升级推荐数（#{SiteSetting.find_by_key('recommander_level_promotion').value}）<a href=\"/admin/recommand_histories\">更多推荐规则历史记录</a>".html_safe
        else
          @notice = "当前处于预览模式，仅用于查看榜单，或预览策略效果，不会即时生效"
        end
      }
      format.csv {
        @recommands = recommands.includes(owners[params[:recommand][:group]]).all
        clean_recommands @recommands, params[:recommand][:group] == 'recommander_id'
        send_data(csv_content_for_index(@recommands),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "推荐统计_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  private

    def setup
      @ways = ["统计","推荐统计"]
      @left_panel = "layouts/statistics_left_panel"
    end

    def csv_content_for_index(objs)
      if params[:recommand][:group] == 'recommander_id'
        header = ["\xEF\xBB\xBF推荐人", '联系方式', '推荐数量']
      else
        header = ["\xEF\xBB\xBF终端", '推荐人', '联系方式', '推荐数量']
      end
      csv_content_for(objs, header) do |record|  
        if params[:recommand][:group] == 'recommander_id'
          [record.recommander.name, record.recommander.mobile_number, record.respond_to?(:total) ? record.total : 0]
        else
          [record.terminal, record.recommander.name, record.recommander.mobile_number, record.total]
        end
      end
    end

    def csv_content_for(objs, header)
      CSV.generate do |csv|  
        csv << header
        objs.each do |record|  
          csv << yield(record)
        end
      end    
    end

    def clean_recommands recommands, for_recommander = true
      # remove non-recommander
      recommands.delete_if { |r| r.recommander.nil? || !r.recommander.is_recommander }

      # add empty recommander
      if for_recommander
        all_recommander = Account.where(is_recommander: true).includes(:account_group)
        current_recommander = recommands.map(&:recommander_id).uniq
        all_recommander.each do |r|
          unless current_recommander.include? r.id
            recommand = Recommand.new(recommander_id: r.id)
            recommand.recommander = r
            recommands << recommand
          end
        end
      end
    end
end